package com.itheima.reggie.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.entity.Page;
import com.itheima.reggie.exception.BusinessException;
import com.itheima.reggie.mapper.EmployeeMapper;
import com.itheima.reggie.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class EmployeeServiceImpl implements EmployeeService {
    @Autowired(required = false)
    private EmployeeMapper employeeMapper;
    /**
     * @param employee
     * @return
     */
    @Override
    public R<Employee> login(Employee employee) {
        Employee loginEmployee = employeeMapper.login(employee);

        if (loginEmployee==null){
            return R.error("用户名或密码错误");
        }

        String userMd5 = DigestUtils.md5DigestAsHex(employee.getPassword().getBytes());

        if (!loginEmployee.getPassword().equals(userMd5)){
            return R.error("用户名或密码错误");
        }
        if (loginEmployee.getStatus()==0){
            return R.error("已被禁用,请联系管理员");
        }
        return R.success(loginEmployee);
    }

    @Override
    public void save(Employee employee) {
        //校验数据用户名是否被注册
        //根据用户名查找用户
        Employee dbEmployee = employeeMapper.login(employee);
        //判断用户是否存在
        if (dbEmployee!=null){
            throw  new BusinessException("用户名已存在");
        }
        //设置默认密码
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
        //设置默认状态
        employee.setStatus(1);
        //设置默认创建与更新时间
        LocalDateTime now = LocalDateTime.now();
        employee.setUpdateTime(now);
        employee.setCreateTime(now);

        employeeMapper.save(employee);

    }

    @Override
    public Page<Employee> findByPage(Integer page, Integer pageSize, String name) {
        PageHelper.startPage(page,pageSize);

        List<Employee> employeeList = employeeMapper.findByName(name);

        PageInfo<Employee> pageInfo = new PageInfo<>(employeeList);
        Page<Employee> pageObj = new Page<>(
                pageInfo.getList(),
                pageInfo.getTotal(),
                pageInfo.getPageSize(),
                pageInfo.getPageNum());


        return pageObj;
    }

    /**
     * 修改用户的方法
     *
     * @param employee
     */
    @Override
    public void update(Employee employee) {
        employee.setUpdateTime(LocalDateTime.now());

        employeeMapper.update(employee);
    }

    /**
     * 根据id查询员工对象
     *
     * @param id
     * @return
     */
    @Override
    public Employee findById(long id) {

        return employeeMapper.findById(id);
    }
}
